import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Condition, UploadFile } from 'custom';
import { Photo } from 'src/common/entities/photo.entity';
import { removeFile } from 'src/utils/qiniu.remove';
import { upload } from 'src/utils/qiniu.upload';
import { Like, Repository } from 'typeorm';
import { DataSource } from 'typeorm/data-source/DataSource';
import { CreateRoomDto } from './dto/create-room.dto';
import { Room } from './entities/room.entity';
const fs = require('fs');
@Injectable()
export class RoomService {
  constructor(
    private dataSource: DataSource,
    @InjectRepository(Room)
    private readonly roomRepository: Repository<Room>,

    @InjectRepository(Photo)
    private readonly photoRepository: Repository<Photo>,
  ) {}

  //创建房间
  async create(createRoomDto: CreateRoomDto, files: UploadFile[]) {
    const fileList = files.map((file) =>
      upload(file.path, 'hotel/' + file.filename),
    );
    try {
      const urlList = await Promise.all(fileList);

      files.forEach((file) => fs.unlinkSync(file.path));

      const photoList = urlList.map((item: { key: string }) => {
        const photo = new Photo();
        photo.url = 'https://wx.tinyxu.fun/' + item.key;
        photo.key = item.key;
        return photo;
      });
      const room = new Room();
      room.name = createRoomDto.name;
      room.info = createRoomDto.info;
      room.price = +createRoomDto.price;
      room.capacity = +createRoomDto.capacity;
      room.bedroom = +createRoomDto.bedroom;
      room.toilet = +createRoomDto.toilet;
      room.hot = +createRoomDto.hot;
      room.air = +createRoomDto.air;
      room.washer = +createRoomDto.washer;
      room.wifi = +createRoomDto.wifi;
      room.pojector = +createRoomDto.pojector;
      room.photos = photoList;
      return await this.roomRepository.save(room);
    } catch (error) {
      throw error;
    }
  }
  //查寻所有
  async findAll() {
    return await this.roomRepository.find({
      relations: ['photos'],
      order: { id: 'DESC' },
    });
  }
  //分页查询
  async findByPage(skip: number, take: number) {
    return await this.roomRepository.find({
      relations: ['photos'],
      order: { id: 'DESC' },
      skip,
      take,
    });
  }
  //查所有条数
  async findCount() {
    return this.roomRepository.createQueryBuilder('room').getCount();
  }

  async getSome(key: number) {
    if (key == 0) {
      //热门
      return await this.roomRepository.find({
        relations: ['photos'],
        where: { hot: 1 },
        order: { id: 'DESC' },
        skip: 0,
        take: 6,
      });
    } else if (key == 1) {
      //推荐
      return await this.roomRepository.find({
        relations: ['photos'],
        order: { price: 'ASC' },
        skip: 0,
        take: 6,
      });
    } else {
      //最新
      return await this.roomRepository.find({
        relations: ['photos'],
        order: { id: 'DESC' },
        skip: 0,
        take: 6,
      });
    }
  }
  //关键词查询
  async findByKeyword(keyword: string) {
    return await this.roomRepository.find({
      relations: ['photos'],
      where: [{ name: Like(`%${keyword}%`) }, { info: Like(`%${keyword}%`) }],
    });
  }
  //查询未被下架的房间
  async findByCondition(condition: Condition) {
    const server = condition.service;
    const roomQueryBuilder = this.roomRepository
      .createQueryBuilder('room')
      .leftJoinAndSelect('room.photos', 'photo')
      .where('room.soldOut = :soldOut', { soldOut: 0 });
    if (server != '') {
      roomQueryBuilder.andWhere(`room.${server}=:servers`, { servers: 1 });
    }
    roomQueryBuilder.andWhere('room.bedroom>=:bedroom', {
      bedroom: condition.bedroom,
    });
    if (Number(condition.price) == 1) {
      roomQueryBuilder.orderBy('room.price', 'ASC');
    }
    if (Number(condition.price) == 2) {
      roomQueryBuilder.orderBy('room.price', 'DESC');
    }
    return await roomQueryBuilder.getMany();
  }

  findOne(id: number) {
    return `This action returns a #${id} room`;
  }

  //更新房间数据
  async update(id: number, updateRoomDto: any) {
    return await this.roomRepository.update(id, updateRoomDto);
  }

  // 房间图片修改
  async updatePhoto(id: number, fileInfo: any) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    //开启事务
    await queryRunner.startTransaction();
    try {
      await queryRunner.manager.delete(Photo, id);
      await removeFile(fileInfo.key);
      //提交事务
      await queryRunner.commitTransaction();
    } catch (error) {
      //回滚事务
      await queryRunner.rollbackTransaction();
    } finally {
      //关闭事务 释放资源
      await queryRunner.release();
    }
    return;
  }
  //添加图片
  async createPhote(file: UploadFile, id: number) {
    try {
      const result = (await upload(file.path, 'hotel/' + file.filename)) as {
        key: string;
      };
      console.log(result);
      await fs.unlinkSync(file.path);
      let photoe = new Photo();
      photoe.key = result.key;
      photoe.url = 'https://wx.tinyxu.fun/' + result.key;
      photoe.room = id as any;
      return await this.photoRepository.save(photoe);
    } catch (error) {
      throw error;
    }
  }
  //删除房间
  async remove(id: number) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    //开启事务
    await queryRunner.startTransaction();

    try {
      const result = await queryRunner.manager
        .createQueryBuilder(Photo, 'photo')
        .where('photo.room_id = :id', { id })
        .getMany();

      await queryRunner.manager.delete(Photo, { room: id });

      const keyList = result.map((item) => removeFile(item.key));
      await Promise.all(keyList);
      await queryRunner.manager.delete(Room, id);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      queryRunner.release();
    }
    return;
  }
}
